/*
 * @Description: UploadController
 * @Author: Jinzhu Liu
 * @Date: 2021-12-22 22:11:40
 * @LastEditor: Jinzhu Liu
 * @LastEditTime: 2021-12-23 00:00:24
 */

import console from "console";
import { File } from "formidable"
import { Context } from "koa";
import fs from "fs"
import response from "../../utils/response";
import path from "path";

function randomString(length: number): string {
    const seader = 'ABCDEFGHJKMNPQRSTWXYabcdefhijkmnprstwxy345678'
    let randomString = ''
    for (let i = 0; i < length; i++) {
        randomString += seader.charAt(Math.floor(Math.random() * seader.length))
    }
    return randomString
}

class UploadController {
    index(ctx: Context) {

    }

    upload(ctx: Context) {
        const file = ctx.request.files?.file as File
        // console.log(file)
        if (file) {
            // @ts-ignore
            const ext = path.extname(file.name)
            const randomName = randomString(32)
            let savePath = '/upload/' + randomName + ext

            const reader = fs.createReadStream(file.path)
            // @ts-ignore
            const writer = fs.createWriteStream('statics' + savePath)

            reader.pipe(writer)
            response.success(ctx, {file: savePath})
        } else {
            response.error(ctx, 'File cannot be null')
        }
    }
}

export default new UploadController